package com.neusoft.satoken.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.net.ssl.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;


@Component
public class HttpSSLClientUtil {

    @Value("${server.ssl.key-store-password}")
    private String password;

    @Value("${server.ssl.trust-store}")
    private String certStorePath;

    private static String pwd;
    private static String certPath;

    @PostConstruct
    public void getPwdAndCertPath(){
        pwd = this.password;
        certPath = this.certStorePath;
    }

    /**
     * 加载密钥，信任库
     *
     * @return
     */
    public static SSLConnectionSocketFactory custom(){
        KeyStore clientStore = null;
        try {
            clientStore = KeyStore.getInstance("PKCS12");
            // 加载客户端证书，即自己的私钥
            clientStore
                    .load(new FileInputStream(certPath),
                            pwd.toCharArray());
            // 创建密钥管理工厂实例
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            // 初始化客户端密钥库

            kmf.init(clientStore, pwd.toCharArray());
            KeyManager[] kms = kmf.getKeyManagers();
            // 创建信任库管理工厂实例
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            // 信任库类型
            KeyStore trustStore = KeyStore.getInstance("PKCS12");
            // 加载信任库，即服务端公钥
            trustStore.load(new FileInputStream(certPath),
                    pwd.toCharArray());
            // 初始化信任库
            tmf.init(trustStore);
            TrustManager[] tms = tmf.getTrustManagers();
            // 建立TLS连接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            // 初始化SSLContext
            sslContext.init(kms, tms, new SecureRandom());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new NoopHostnameVerifier());

            return sslsf;
        } catch (KeyStoreException | FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     *  post 请求
     * @param url
     * @param json
     * @return
     */
    public static String doPostJson(String url, String json) {
        SSLConnectionSocketFactory sslConnectSocket = HttpSSLClientUtil.custom();
        //创建自定义的httpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectSocket).build();

        CloseableHttpResponse response=null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     *  get 请求
     * @param url
     * @return
     */
    public static String doGet(String url) {

        SSLConnectionSocketFactory sslConnectSocket = HttpSSLClientUtil.custom();
        //创建自定义的httpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectSocket).build();
        CloseableHttpResponse response=null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpGet httpGet = new HttpGet(url);
            // 执行http请求
            response = httpClient.execute(httpGet);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }
}
